package servlet.admin;

import dao.UserDao;
import dao.service.UserDaoImp;
import modle.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author cloudJiang
 * @date 2021/10/11 17:33
 */

@WebServlet("/manage/adminDoUserDel")
public class DoUserDel extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userID = request.getParameter("id");
        System.out.println("-----------------------" + userID);

        UserDao userDao = new UserDaoImp();

        //成功或失败从定向
        if (userDao.delUser(userID)) {
            System.out.println("删除成功.");
            //插入成功则定向到User文件

            System.out.println(request.getParameter("page"));
            response.sendRedirect("adminDoUserGet?cp=" + request.getParameter("page"));
        } else {
            //获取返回流
            PrintWriter out = response.getWriter();

            out.write("<script>");
            out.write("alert('用户删除失败')");
            out.write("location.href='manage/adminDoUserGet?cp=" + request.getParameter("page") + "'");
            out.write("</script>");
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String[] userIDs = request.getParameterValues("id[]");
        UserDao userDao = new UserDaoImp();
        boolean flag = true;

        if (userIDs != null) {
            for (String userID : userIDs) {
                if (userDao.delUser(userID)) {
                } else {
                    flag = false;
                    System.out.println("删除用户" + userID + "失败");
                }
            }
        } else {
            flag = false;
        }

        //成功或失败从定向
        if (flag) {
            System.out.println("删除成功.");
            //插入成功则定向到User文件

            System.out.println(request.getParameter("cp"));
            response.sendRedirect("adminDoUserGet?cp=" + request.getParameter("cp"));
        } else {
            //获取返回流

            PrintWriter out = response.getWriter();

            out.write("<script>");
            out.write("alert('用户删除失败')");
            out.write("location.href='manage/adminDoUserGet?cp=" + request.getParameter("page") + "'");
            out.write("</script>");
            System.out.println("失败");
            out.close();
        }
    }
}
